package test2;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    public Socket socket = null;
    public TcpEchoClient(String serverIp,int serverPort) throws IOException {
        socket = new Socket(serverIp,serverPort);
    }
    public void start() throws IOException {
        System.out.println("客户端上线！");
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            Scanner scanner = new Scanner(inputStream);
            Scanner scannerin = new Scanner(System.in);
            PrintWriter printWriter = new PrintWriter(outputStream);
            while(true){

                System.out.print("->");
                String request = scannerin.next();
                printWriter.println(request);
                printWriter.flush();
                // 3. 从服务器读取响应
                if (!scanner.hasNext()) {
                    break;
                }
                String resposne = scanner.next();
                System.out.println(resposne);
            }
        }catch (IOException e ){
            e.printStackTrace();
        }finally {
            socket.close();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient t = new TcpEchoClient("127.0.0.1",9090);
        t.start();
    }
}
